package com.cxs.rdbdemo.slice;

import com.cxs.rdbdemo.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.data.DatabaseHelper;
import ohos.data.rdb.*;
import ohos.data.resultset.ResultSet;


public class MainAbilitySlice extends AbilitySlice {

    RdbStore rdbStore;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        DatabaseHelper helper = new DatabaseHelper(this);

        // 创建数据库，前提：先要准备数据库配置信息，简单起见只配置数据库名字。其他都为默认值
        StoreConfig storeConfig = StoreConfig.newDefaultConfig("RdbStoreTest.db");
        RdbOpenCallback callback = new RdbOpenCallback() {
            @Override
            public void onCreate(RdbStore rdbStore) {
                rdbStore.executeSql("CREATE TABLE IF NOT EXISTS table_test" +
                        "(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, age INTEGER, salary REAL)");
            }

            @Override
            public void onUpgrade(RdbStore rdbStore, int i, int i1) {

            }
        };

        /*
            通过helper的方法，来获取到数据库对象,getRdbStore()：如果数据库不存在，自动创建
            storeConfig：数据库配置信息
            version：我们使用的数据库的版本，整数
            openCallBack：创建数据库时被回调，可以在该方法中初始化表结构，并添加一些应用使用到的初始化数据
            resultSetHook（勾子）：把要发送的信息勾住，然后进行各种处理，再发送出去
         */
        rdbStore = helper.getRdbStore(storeConfig, 1, callback, null);

        initView();
    }

    private void initView() {
        findComponentById(ResourceTable.Id_btn_insert).setClickedListener(c -> insertDB());
        findComponentById(ResourceTable.Id_btn_query).setClickedListener(c -> queryDB());
        findComponentById(ResourceTable.Id_btn_update).setClickedListener(c -> updateDB());
        findComponentById(ResourceTable.Id_btn_delete).setClickedListener(c -> deleteDB());
    }

    private void deleteDB() {
        rdbStore.executeSql("DELETE FROM table_test WHERE age=?", new Object[]{"18"});

//        RdbPredicates rdbPredicates = new RdbPredicates("table_test").equalTo("name", "zhangsan");
//        int num = rdbStore.delete(rdbPredicates);
//        System.out.println("================num: " + num);
    }

    private void queryDB() {
        RdbPredicates rdbPredicates = new RdbPredicates("table_test")
                .orderByAsc("salary");
        String[] cols = {"id", "name", "age", "salary"};
        ResultSet query = rdbStore.query(rdbPredicates, cols);

        while (query.goToNextRow()) {
            System.out.println("============ id:" + query.getInt(query.getColumnIndexForName("id")));
            System.out.println("============ name:" + query.getString(query.getColumnIndexForName("name")));
            System.out.println("============ age:" + query.getInt(query.getColumnIndexForName("age")));
            System.out.println("============ salary:" + query.getFloat(query.getColumnIndexForName("salary")));
        }
    }

    private void insertDB() {
        rdbStore.executeSql("insert into table_test ('name', 'age', 'salary') values('王五', '28', 5637.3)");
        ValuesBucket vb = new ValuesBucket();
        vb.putString("name", "zhangsan");
        vb.putInteger("age", 18);
        vb.putDouble("salary", 8673.56);
        long rowId1 = rdbStore.insert("table_test", vb);  // 返回的是记录的行数，不是id

    }

    private void updateDB() {
//        ValuesBucket vb = new ValuesBucket();
//        vb.putString("name", "张三");
//        RdbPredicates rdbPredicates = new RdbPredicates("table_test").equalTo("age", 18);
//        int count = rdbStore.update(vb, rdbPredicates);
//        System.out.println("============count: " + count);
        rdbStore.executeSql("UPDATE table_test set name='张发发' where name=?", new Object[]{"zhangsan"});
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
